<template>
	<div>


		<!--统计卡片区域-->
		<div class="statistics-card-container">
			<el-card shadow="hover" class="statistics-card">
				<div slot="header" class="statistics-card-header">
					<span>任务总数</span>
				</div>
				<div class="statistics-card-content">
					<div class="statistics-card-number">{{ statistics_data.totalTasks }}</div>
					<div class="statistics-card-desc">本期创建的巡检任务数量</div>
				</div>
			</el-card>

			<el-card shadow="hover" class="statistics-card">
				<div slot="header" class="statistics-card-header">
					<span>已完成任务</span>
				</div>
				<div class="statistics-card-content">
					<div class="statistics-card-number">{{ statistics_data.completedTasks }}</div>
					<div class="statistics-card-desc">已完成的巡检任务数量</div>
				</div>
			</el-card>

			<el-card shadow="hover" class="statistics-card">
				<div slot="header" class="statistics-card-header">
					<span>待完成任务</span>
				</div>
				<div class="statistics-card-content">
					<div class="statistics-card-number">{{ statistics_data.pendingTasks }}</div>
					<div class="statistics-card-desc">待处理的巡检任务数量</div>
				</div>
			</el-card>

			<el-card shadow="hover" class="statistics-card">
				<div slot="header" class="statistics-card-header">
					<span>任务完成率</span>
				</div>
				<div class="statistics-card-content">
					<div class="statistics-card-number">{{ statistics_data.completionRate }}%</div>
					<div class="statistics-card-desc">任务完成百分比</div>
				</div>
			</el-card>
		</div>

		<!--图表区域-->
		<div class="charts-container">
			<el-card shadow="hover" class="chart-card">
				<div slot="header" class="chart-card-header">
					<span>任务状态分布</span>
				</div>
				<div class="chart-content">
					<el-row>
						<el-col :span="12">
							<div id="taskStatusChart" style="height: 300px;"></div>
						</el-col>
						<el-col :span="12">
							<div id="taskTypeChart" style="height: 300px;"></div>
						</el-col>
					</el-row>
				</div>
			</el-card>

			<el-card shadow="hover" class="chart-card">
				<div slot="header" class="chart-card-header">
					<span>任务趋势分析</span>
				</div>
				<div class="chart-content">
					<div id="taskTrendChart" style="height: 400px;"></div>
				</div>
			</el-card>

			<el-card shadow="hover" class="chart-card">
				<div slot="header" class="chart-card-header">
					<span>任务完成情况</span>
				</div>
				<el-table
						:data="task_table_data"
						tooltip-effect="dark"
						style="width: 100%"
						border
						stripe>

					<el-table-column
							prop="taskName"
							label="任务名称">
					</el-table-column>
					<el-table-column
							prop="taskType"
							label="任务类型">
						<template slot-scope="scope">
							<el-tag size="small" v-if="scope.row.taskType === 1" type="primary">定期巡检</el-tag>
							<el-tag size="small" v-else-if="scope.row.taskType === 2" type="success">专项巡检</el-tag>
						</template>
					</el-table-column>
					<el-table-column
							prop="startDate"
							label="开始时间">
					</el-table-column>
					<el-table-column
							prop="endDate"
							label="结束时间">
					</el-table-column>
					<el-table-column
							prop="status"
							label="任务状态">
						<template slot-scope="scope">
							<el-tag size="small" v-if="scope.row.status === 0" type="info">待执行</el-tag>
							<el-tag size="small" v-else-if="scope.row.status === 1" type="success">已完成</el-tag>
							<el-tag size="small" v-else-if="scope.row.status === 2" type="warning">进行中</el-tag>
							<el-tag size="small" v-else-if="scope.row.status === 3" type="danger">已超时</el-tag>
						</template>
					</el-table-column>
					<el-table-column
							prop="executorName"
							label="执行人员">
					</el-table-column>
					<el-table-column
							prop="completionRate"
							label="完成进度">
							<template slot-scope="scope">
								<el-progress :percentage="scope.row.completionRate" :stroke-width="10" :show-text="true"></el-progress>
							</template>
					</el-table-column>
				</el-table>
				<el-pagination
						@size-change="handle_size_change"
						@current-change="handle_current_change"
						layout="total, sizes, prev, pager, next, jumper"
						:page-sizes="[10, 20, 50, 100]"
						:current-page="current_page"
						:page-size="page_size"
						:total="task_total" class="mt-20">
				</el-pagination>
			</el-card>
		</div>
	</div>
</template>

<script>
	import statisticsApi from '@/api/data-statistics.js'
	import * as echarts from 'echarts'
	export default {
		name: "TaskStatistics",
		data() {
			return {
				total: 0,
				page_size: 10,
				current_page: 1,
				task_total: 0,

				statistics_data: {
					total_tasks: 0,
					completed_tasks: 0,
					pending_tasks: 0,
					completion_rate: 0
				},
				task_table_data: [],

				// 图表实例
				task_status_chart: null,
				task_type_chart: null,
				task_trend_chart: null
			}
		},
		mounted() {
			this.get_data()
			// 监听窗口大小变化，重新调整图表大小
			window.addEventListener('resize', this.resize_charts)
		},
		destroyed() {
			window.removeEventListener('resize', this.resize_charts)
			// 销毁图表实例
			if (this.task_status_chart) {
				this.task_status_chart.dispose()
			}
			if (this.task_type_chart) {
				this.task_type_chart.dispose()
			}
			if (this.task_trend_chart) {
				this.task_trend_chart.dispose()
			}
		},
		methods: {
			format_date(date) {
				const year = date.getFullYear()
				const month = String(date.getMonth() + 1).padStart(2, '0')
				const day = String(date.getDate()).padStart(2, '0')
				return `${year}-${month}-${day}`
			},

			get_data() {
				// 获取所有任务数据进行统计
				statisticsApi.taskStatistics().then(res => {
					const tasks = res.data.records || []
					
					// 计算统计数据
					const total_tasks = tasks.length
					const completed_tasks = tasks.filter(task => task.status === 1).length // 状态1表示已完成
					const pending_tasks = tasks.filter(task => task.status === 0).length // 状态0表示待执行
					const in_progress_tasks = tasks.filter(task => task.status === 2).length // 状态2表示进行中
					const overdue_tasks = tasks.filter(task => task.status === 3).length // 状态3表示已超时
					const regular_tasks = tasks.filter(task => task.task_type === 1).length // 定期巡检
					const special_tasks = tasks.filter(task => task.task_type === 2).length // 专项巡检
					const completion_rate = total_tasks > 0 ? Math.round((completed_tasks / total_tasks) * 100) : 0
					
					// 准备趋势图数据（最近7天）
					const date_labels = []
					const new_task_data = []
					const completed_task_data = []
					for (let i = 6; i >= 0; i--) {
						const date = new Date()
						date.setDate(date.getDate() - i)
						const date_str = this.format_date(date)
						date_labels.push(date_str)
						
						// 基于实际任务数据统计（按创建日期统计新建任务，按完成日期统计已完成任务）
						const new_tasks = tasks.filter(task => {
							const task_date = task.createTime ? this.format_date(new Date(task.createTime)) : ''
							return task_date === date_str
						}).length
						
						const completed_tasks = tasks.filter(task => {
							const task_date = task.completeTime ? this.format_date(new Date(task.completeTime)) : ''
							return task.status === 1 && task_date === date_str
						}).length
						
						new_task_data.push(new_tasks)
						completed_task_data.push(completed_tasks)
					}
					
					this.statistics_data = {
						totalTasks: total_tasks,
						completedTasks: completed_tasks,
						pendingTasks: pending_tasks,
						completionRate: completion_rate,
						inProgressTasks: in_progress_tasks,
						overdueTasks: overdue_tasks,
						regularTasks: regular_tasks,
						specialTasks: special_tasks,
						date_labels: date_labels,
						new_task_data: new_task_data,
						completed_task_data: completed_task_data
					}

					// 初始化图表
					this.init_charts(this.statistics_data)
				})

				// 获取任务列表
				this.get_task_list()
			},

			get_task_list() {
				// 获取所有数据后在前端进行处理
				statisticsApi.taskStatistics().then(res => {
					let tasks = res.data.records || []
					
					// 处理分页
					this.task_total = tasks.length
					const start = (this.current_page - 1) * this.page_size
					const end = start + this.page_size
					this.task_table_data = tasks.slice(start, end).map(task => ({
						...task,
						startDate: task.startTime ? new Date(task.startTime).toLocaleDateString() : '',
						endDate: task.endTime ? new Date(task.endTime).toLocaleDateString() : '',
						// 添加一些表格需要的额外字段
						status: task.status || 0, // 确保status字段存在
						completionRate: task.status === 1 ? 100 : task.status === 2 ? 50 : 0 // 模拟完成进度
					}))
				})
			},

			handle_size_change(val) {
				this.page_size = val
				this.get_task_list()
			},
			handle_current_change(val) {
				this.current_page = val
				this.get_task_list()
			},

			resize_charts() {
				if (this.task_status_chart) {
					this.task_status_chart.resize()
				}
				if (this.task_type_chart) {
					this.task_type_chart.resize()
				}
				if (this.task_trend_chart) {
					this.task_trend_chart.resize()
				}
			},

			init_charts(chart_data) {
				// 任务状态分布图表
				if (!this.task_status_chart) {
					this.task_status_chart = echarts.init(document.getElementById('taskStatusChart'))
				}

				const statusOption = {
					title: {
						text: '任务状态分布',
						subtext: '',
						left: 'center'
					},
					tooltip: {
						trigger: 'item',
						formatter: '{a} <br/>{b}: {c} ({d}%)'
					},
					legend: {
						orient: 'vertical',
						left: 'left',
					},
					series: [
						{
							name: '任务状态',
							type: 'pie',
							radius: '50%',
							data: [
								{value: chart_data.pendingTasks || 0, name: '待执行'},
								{value: chart_data.completedTasks || 0, name: '已完成'},
								{value: chart_data.inProgressTasks || 0, name: '进行中'},
								{value: chart_data.overdueTasks || 0, name: '已超时'}
							],
							emphasis: {
								itemStyle: {
									shadowBlur: 10,
									shadowOffsetX: 0,
									shadowColor: 'rgba(0, 0, 0, 0.5)'
								}
							}
						}
					]
				}
				this.task_status_chart.setOption(statusOption)

				// 任务类型分布图表
				if (!this.task_type_chart) {
					this.task_type_chart = echarts.init(document.getElementById('taskTypeChart'))
				}

				const typeOption = {
					title: {
						text: '任务类型分布',
						subtext: '',
						left: 'center'
					},
					tooltip: {
						trigger: 'item',
						formatter: '{a} <br/>{b}: {c} ({d}%)'
					},
					legend: {
						orient: 'vertical',
						left: 'left',
					},
					series: [
						{
							name: '任务类型',
							type: 'pie',
							radius: '50%',
							data: [
								{value: chart_data.regularTasks || 0, name: '定期巡检'},
								{value: chart_data.specialTasks || 0, name: '专项巡检'}
							],
							emphasis: {
								itemStyle: {
									shadowBlur: 10,
									shadowOffsetX: 0,
									shadowColor: 'rgba(0, 0, 0, 0.5)'
								}
							}
						}
					]
				}
				this.task_type_chart.setOption(typeOption)

				// 任务趋势分析图表
				if (!this.task_trend_chart) {
					this.task_trend_chart = echarts.init(document.getElementById('taskTrendChart'))
				}

				const trendOption = {
					title: {
						text: '任务完成趋势',
						subtext: '最近7天新建与完成任务统计',
						left: 'center'
					},
					tooltip: {
						trigger: 'axis',
						formatter: function(params) {
							let result = params[0].name + '<br/>'
							params.forEach(param => {
								result += `${param.marker}${param.seriesName}: ${param.value}<br/>`
							})
							return result
						}
					},
					legend: {
						data: ['新建任务', '完成任务'],
						bottom: 0
					},
					grid: {
						left: '3%',
						right: '4%',
						bottom: '15%',
						containLabel: true
					},
					xAxis: {
						type: 'category',
						boundaryGap: false,
						data: chart_data.date_labels || [],
						axisLabel: {
							rotate: 45
						}
					},
					yAxis: {
						type: 'value',
						name: '任务数量',
						min: 0
					},
					series: [
						{
							name: '新建任务',
							type: 'line',
							symbol: 'circle',
							symbolSize: 8,
							itemStyle: {
								color: '#409EFF'
							},
							lineStyle: {
								width: 3
							},
							areaStyle: {
								color: {
									type: 'linear',
									x: 0, y: 0, x2: 0, y2: 1,
									colorStops: [
										{offset: 0, color: 'rgba(64, 158, 255, 0.3)'},
										{offset: 1, color: 'rgba(64, 158, 255, 0.05)'}
									]
								}
							},
							data: chart_data.new_task_data || []
						},
						{
							name: '完成任务',
							type: 'line',
							symbol: 'circle',
							symbolSize: 8,
							itemStyle: {
								color: '#67C23A'
							},
							lineStyle: {
								width: 3
							},
							areaStyle: {
								color: {
									type: 'linear',
									x: 0, y: 0, x2: 0, y2: 1,
									colorStops: [
										{offset: 0, color: 'rgba(103, 194, 58, 0.3)'},
										{offset: 1, color: 'rgba(103, 194, 58, 0.05)'}
									]
								}
							},
							data: chart_data.completed_task_data || []
						}
					]
				}
				this.task_trend_chart.setOption(trendOption)
			}
		}
	}
</script>

<style scoped>
	.statistics-card-container {
		display: flex;
		gap: 20px;
		margin-top: 20px;
		margin-bottom: 20px;
	}

	.statistics-card {
		flex: 1;
	}

	.statistics-card-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.statistics-card-content {
		text-align: center;
		padding: 10px 0;
	}

	.statistics-card-number {
		font-size: 36px;
		font-weight: bold;
		color: #409EFF;
		margin-bottom: 10px;
	}

	.statistics-card-desc {
		font-size: 14px;
		color: #606266;
	}

	.charts-container {
		margin-top: 20px;
	}

	.chart-card {
		margin-bottom: 20px;
	}

	.chart-card-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.chart-content {
		padding: 20px 0;
	}

	.mt-20 {
		margin-top: 20px;
	}
</style>